<template>
  <div class="config-panel">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button
        type="primary"
        @click="testConnection"
        :loading="testing"
        icon="Connection"
      >
        测试连接
      </el-button>
      <el-button
        @click="refreshConfig"
        :loading="loading"
        icon="Refresh"
      >
        刷新配置
      </el-button>
    </div>

    <!-- 连接状态 -->
    <div class="connection-status" v-if="connectionStatus !== null">
      <el-alert
        :title="connectionStatus.message"
        :type="connectionStatus.connected ? 'success' : 'error'"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 当前环境配置 -->
    <div class="current-config" v-if="currentConfig">
      <h4>当前环境: {{ currentConfig.environment }}</h4>
      <el-descriptions :column="2" border>
        <el-descriptions-item
          v-for="(value, key) in currentConfig.config"
          :key="key"
          :label="formatLabel(String(key))"
        >
          <span v-if="String(key).includes('password') || String(key).includes('secret') || String(key).includes('key')">
            {{ maskSensitiveData(value) }}
          </span>
          <span v-else>{{ value }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 所有环境配置 -->
    <div class="all-configs" v-if="allConfigs">
      <h4>所有环境配置</h4>
      <el-collapse v-model="activeNames">
        <el-collapse-item
          v-for="(config, env) in filteredConfigs"
          :key="env"
          :title="`${formatEnvName(env)} 环境`"
          :name="env"
        >
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item
              v-for="(value, key) in config"
              :key="key"
              :label="formatLabel(String(key))"
            >
              <span v-if="String(key).includes('password') || String(key).includes('secret') || String(key).includes('key')">
                {{ maskSensitiveData(value) }}
              </span>
              <span v-else>{{ value }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 系统信息 -->
    <div class="system-info" v-if="allConfigs">
      <h4>系统信息</h4>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="当前时间">
          {{ formatTimestamp(allConfigs.timestamp) }}
        </el-descriptions-item>
        <el-descriptions-item label="当前环境">
          {{ allConfigs.currentEnvironment }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { ping, getConfig, getCurrentConfig } from '../api/redis'

// 响应式数据
const loading = ref(false)
const testing = ref(false)
const connectionStatus = ref<any>(null)
const currentConfig = ref<any>(null)
const allConfigs = ref<any>(null)
const activeNames = ref<string[]>(['local'])

// 格式化标签名
const formatLabel = (key: string) => {
  const labelMap: Record<string, string> = {
    host: '主机地址',
    port: '端口',
    database: '数据库',
    password: '密码',
    endpoint: '端点',
    mode: '模式',
    accessKey: '访问密钥',
    secretKey: '密钥',
    region: '区域',
    instanceId: '实例ID',
    vpcId: 'VPC ID'
  }
  return labelMap[key] || key
}

// 格式化环境名
const formatEnvName = (env: string) => {
  const envMap: Record<string, string> = {
    local: '本地',
    aliyun: '阿里云',
    huawei: '华为云',
    tencent: '腾讯云'
  }
  return envMap[env] || env
}

// 脱敏处理敏感数据
const maskSensitiveData = (value: any) => {
  if (!value || typeof value !== 'string') return value
  if (value.length <= 4) return '****'
  return value.substring(0, 2) + '****' + value.substring(value.length - 2)
}

// 格式化时间戳
const formatTimestamp = (timestamp: number) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 过滤配置（排除系统字段）
const filteredConfigs = computed(() => {
  if (!allConfigs.value) return {}
  const { currentEnvironment, timestamp, ...configs } = allConfigs.value
  return configs
})

// 测试连接
const testConnection = async () => {
  testing.value = true
  try {
    const response = await ping()
    connectionStatus.value = response.data
    ElMessage.success('连接测试完成')
  } catch (error: any) {
    connectionStatus.value = {
      connected: false,
      message: '连接失败: ' + (error.response?.data?.message || error.message)
    }
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 刷新配置
const refreshConfig = async () => {
  loading.value = true
  try {
    // 并行获取配置信息
    const [configResponse, currentResponse] = await Promise.all([
      getConfig(),
      getCurrentConfig()
    ])

    allConfigs.value = configResponse.data
    currentConfig.value = currentResponse.data

    ElMessage.success('配置信息已刷新')
  } catch (error: any) {
    ElMessage.error('获取配置失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载配置
onMounted(() => {
  refreshConfig()
})
</script>

<style scoped>
.config-panel {
  padding: 0;
}

.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.connection-status {
  margin-bottom: 20px;
}

.current-config,
.all-configs,
.system-info {
  margin-bottom: 25px;
}

.current-config h4,
.all-configs h4,
.system-info h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-collapse-item__header) {
  font-weight: 600;
}

:deep(.el-descriptions) {
  margin-bottom: 0;
}

/* 对话框内的样式优化 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item) {
  margin-bottom: 10px;
}

:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}
</style>